package monitor

import (
	"net/http"
	"strconv"
	"time"

	"main/general"
	"main/handlers"

	"github.com/gin-gonic/gin"
)

// DataEntry 结构体表示单个数据项
type DataEntry struct {
	Label string   `json:"label"`
	Data  []string `json:"data"`
}

// Resource 结构体表示资源监控数据
type Resource struct {
	DataTime []string    `json:"data_time"`
	Data     []DataEntry `json:"data"`
}

// Response 结构体表示整个响应
type Response struct {
	CPU    Resource `json:"cpu"`
	Memory Resource `json:"memory"`
	Disk   Resource `json:"disk"`
}

// updateHostData 更新主机监控数据
func updateHostData(valueCode string, hostName string, valueStr string, formattedDate string, response *Response) {
	var dataTimeSlice *[]string
	var dataSlice *[]DataEntry

	// 根据 valueCode 确定是 CPU、Memory 还是 Disk
	switch valueCode {
	case "host_cpu":
		dataTimeSlice = &response.CPU.DataTime
		dataSlice = &response.CPU.Data
	case "host_memory":
		dataTimeSlice = &response.Memory.DataTime
		dataSlice = &response.Memory.Data
	case "host_disk":
		dataTimeSlice = &response.Disk.DataTime
		dataSlice = &response.Disk.Data
	default:
		return // 如果 valueCode 不是预期的值，直接返回
	}

	// 检查日期是否已存在
	dateExists := general.Contains(*dataTimeSlice, formattedDate)
	if !dateExists {
		// 日期不存在，添加新日期
		*dataTimeSlice = append(*dataTimeSlice, formattedDate)
	}

	// 使用 map 来存储现有的主机数据，以便快速查找
	hostMap := make(map[string]*DataEntry)
	for i := range *dataSlice {
		hostMap[(*dataSlice)[i].Label] = &(*dataSlice)[i]
	}

	// 检查主机是否存在
	if entry, exists := hostMap[hostName]; exists {
		// 更新已存在的主机数据
		if len(entry.Data) < len(*dataTimeSlice) {
			// 如果日期已经存在，添加新数据
			entry.Data = append(entry.Data, valueStr)
		} else {
			// 如果日期以上一个时间存在，更新最后一个值
			entry.Data[len(entry.Data)-1] = valueStr
		}
	} else {
		// 如果主机不存在，创建新条目
		newData := make([]string, len(*dataTimeSlice)-1) // 初始化为空字符串数组
		datatmpentry := DataEntry{
			Label: hostName,
			Data:  append(newData, valueStr), // 在末尾添加实际值
		}
		*dataSlice = append(*dataSlice, datatmpentry)
	}

	// 确保其它主机在日期不存在时填充空字符串
	if !dateExists {
		for i := range *dataSlice {
			if len((*dataSlice)[i].Data) < len(*dataTimeSlice) {
				(*dataSlice)[i].Data = append((*dataSlice)[i].Data, "")
			}
		}
	}
}

// GetProjectBaseMeritList 处理获取告警数据的请求
func GetProjectBaseMeritList(c *gin.Context) {
	projectIDStr := c.Query("project_id")
	projectID, err := strconv.Atoi(projectIDStr)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid project ID"})
		return
	}

	// 构建 SQL 查询
	query := `  
		SELECT
			a.project_id,
			a.host_id,
			a.host_name,
			ac.alarm_config_id,
			DATE(ac.alarm_event_time) AS alarm_date,  -- 只取日期部分
			MAX(CASE 
					WHEN ac.alarm_config_id = a.host_cpu_alarm_config THEN ac.alarm_event_result_status 
					ELSE NULL 
				END) AS max_cpu_alarm_event_result_status,
			MAX(CASE 
					WHEN ac.alarm_config_id = a.host_mem_alarm_config THEN ac.alarm_event_result_status 
					ELSE NULL 
				END) AS max_mem_alarm_event_result_status,
			MAX(CASE 
					WHEN ac.alarm_config_id = a.host_disk_alarm_config THEN ac.alarm_event_result_status 
					ELSE NULL 
				END) AS max_disk_alarm_event_result_status
		FROM
			hosts a
		LEFT JOIN
			alarm_event ac
			ON (
				a.host_cpu_alarm_config = ac.alarm_config_id
				OR a.host_mem_alarm_config = ac.alarm_config_id
				OR a.host_disk_alarm_config = ac.alarm_config_id
			)
		WHERE
			ac.alarm_event_time >= NOW() - INTERVAL 1 WEEK
			AND a.project_id = ?
		GROUP BY
			a.project_id,
			a.host_id,
			a.host_name,
			ac.alarm_config_id,
			alarm_date
		ORDER BY
			a.host_id,
			alarm_date ASC;
	`

	// 执行查询
	results, err := handlers.ExecuteQuery(query, projectID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Error executing query", "details": err.Error()})
		return
	}

	// 转换查询结果
	response := Response{
		CPU:    Resource{DataTime: []string{}, Data: []DataEntry{}},
		Memory: Resource{DataTime: []string{}, Data: []DataEntry{}},
		Disk:   Resource{DataTime: []string{}, Data: []DataEntry{}},
	}

	timeMap := make(map[string]struct{})
	for _, row := range results {
		// 将 []byte 转换为 string
		hostName := row["host_name"].(string)

		// 将时间格式化为字符串
		reportedTime := row["alarm_date"].(time.Time)
		formattedDate := reportedTime.Format("20060102")
		timeMap[formattedDate] = struct{}{}

		// 检查和处理 CPU 状态
		cpuStatus, ok := row["max_cpu_alarm_event_result_status"].(string)
		if ok && cpuStatus != "" { // 确保值有效
			updateHostData("host_cpu", hostName, cpuStatus, formattedDate, &response)
		}

		// 检查和处理内存状态
		memStatus, ok := row["max_mem_alarm_event_result_status"].(string)
		if ok && memStatus != "" { // 确保值有效
			updateHostData("host_memory", hostName, memStatus, formattedDate, &response)
		}

		// 检查和处理硬盘状态
		diskStatus, ok := row["max_disk_alarm_event_result_status"].(string)
		if ok && diskStatus != "" { // 确保值有效
			updateHostData("host_disk", hostName, diskStatus, formattedDate, &response)
		}

	}

	c.JSON(http.StatusOK, response) // 返回转换后的响应
}
